import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import useUserStore from '@/stores/modules/user'
import { TOKEN } from '@/constants'
import { load } from '@/utils/loading'
import userRoutes from './modules/user'
// 1.单独使用 loadingBar 进度条
import { createDiscreteApi } from 'naive-ui'
const { loadingBar } = createDiscreteApi(['loadingBar'], {
  loadingBarProviderProps: {
    themeOverrides: {
      colorLoading: '#1890ff'
    }
  }
})

let userStore = null

let routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/User/Login/index.vue')
  },
  {
    path: '/linkShare',
    name: 'linkShare',
    meta: {
      title: '外链分享',
      auth: false
    },
    component: () => import('@/views/User/Share/index.vue')
  }
]

export const errRouter = {
  path: '/:pathMatch(.*)',
  name: 'notFound',
  component: () => import('@/views/NotFound/index.vue')
}

routes = routes.concat(userRoutes)

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 无需权限的页面
const tokenPage = ['/linkShare', '/login']

router.beforeEach(async (to, from, next) => {
  console.log(to.path)

  // 判读是否有token权限
  // 在路由切换前显示进度条
  loadingBar.start()
  load.show()
  const notNeedAuth = tokenPage.some((item) => to.path.indexOf(item) !== -1)
  if (notNeedAuth) {
    next()
  } else {
    const token = localStorage.getItem(TOKEN)
    if (token) {
      userStore = useUserStore()
      // 看动态路由是否已经添加
      if (userStore.isLoadRoute) {
        next()
      } else {
        // 进行动态路由的添加
        const asyncRoutes = await userStore.setAsyncRoutes()
        router.addRoute(asyncRoutes[0])
        router.addRoute(errRouter)
        next({ ...to, replace: true })
      }
    } else {
      next({
        name: 'login'
      })
    }
  }
})

router.afterEach(() => {
  // 在路由加载完成后隐藏进度条
  load.hide()
  loadingBar.finish()
})

export default router
